package com.zqxq.file.controller;

import com.amazonaws.util.IOUtils;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.NumUtils;
import com.zqxq.file.config.FileConfig;
import com.zqxq.file.service.IUploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 说    明：   文件上传
 * 创 建 人：	一刀·胡
 * 创建时间：	2018/3/21 11:24
 * 修 改 人：
 * 修改日期：
 **/
@RestController
@RequestMapping(value="/file",produces = "application/json")
@Slf4j
public class FileController {
    @Autowired
    private FileConfig fileConfig;

    @Resource(name="uploadFileServiceImplPublic")
    private IUploadFileService uploadFileServiceImplPublic;

    @Resource(name="uploadFileServiceImplPrivate")
    private IUploadFileService uploadFileServicePrivate;


    /**
     * 公有上传到S3
     * @param file
     * @return
     */
    @RequestMapping(value = "/saveUserFilePub")
    public Result<String> saveUserFilePub(MultipartFile file, String appKey){
        log.info("图片信息为："+file.getOriginalFilename());
        Result<String> result = new Result();
        try {
            //后缀可以传可以不传 不传的话或根据file自动进行判断 获取出后缀
            String imgurl=uploadFileServiceImplPublic.uploadToS3(file, appKey,null);
            result.setData(imgurl);
        } catch (Exception e) {
            log.info("上传失败:{}",e);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("上传失败");
        }
        return result;
    }

    /**
     * 私有上传到S3
     * @param file
     * @return
     */
    @RequestMapping(value = "/saveUserFilePr")
    public Result<String> saveUserFilePr(MultipartFile file, String appKey){
        log.info("图片信息为："+file.getOriginalFilename());
        Result<String> result = new Result();
        try {
            //后缀可以传可以不传 不传的话或根据file自动进行判断 获取出后缀
            String imgurl=uploadFileServicePrivate.uploadToS3(file, appKey,null);
            result.setData(imgurl);
        } catch (Exception e) {
            log.info("上传失败:{}",e);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("上传失败");
        }
        return result;
    }

    /**
     * 新版上传文件
     * @param fileMap
     * @param appKey
     * @param pathType
     * @return
     */
    @PostMapping(value = "/fileUpload")
    public Result fileUploadNew(@RequestBody Map<String, File> fileMap, @RequestParam("fileName") String fileName, @RequestParam("appKey") String appKey,
                                @RequestParam("path") String path, @RequestParam("pathType") String pathType) {
        Result result = new Result();
        File file = fileMap.get("image_ref1");
        try {
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, "text/plain", IOUtils.toByteArray(input));
            //存储路径前缀
            if(pathType.equals("public")){
                result = this.saveUserFilePub(multipartFile, appKey);
            } else{
                result = this.saveUserFilePr(multipartFile, appKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (CodeEnum.isSuccess(result.getCode())) {
            return result;
        }
        String storageUrl = result.getData().toString();
        log.info("fileUploadNew图片访问的地址为：" + storageUrl);
        Map map = new HashMap();
        map.put("storageUrl", storageUrl);
        map.put("relativeUrl","/"+appKey + storageUrl.substring(storageUrl.lastIndexOf('/')));
        result.setData(map);
        return result;
    }

    /**
     * 测试用的:上传到本地
     * @param fileMap
     * @return
     */
    @RequestMapping(value = "/saveUserFile")
    public Result saveUserFile(@RequestBody Map<String, File> fileMap, @RequestParam("fileName") String fileName, @RequestParam("appKey") String appKey,
                               @RequestParam("path") String path, @RequestParam("pathType") String pathType) throws Exception{
        Result result = new Result();
        //存储路径前缀
        String relativePath = "";
        if(pathType.equals("public")){
            relativePath += fileConfig.getFile_diskPath_public();
        }
        else{
            relativePath += fileConfig.getFile_diskPath_private();
        }

        //存储路径后缀
        String filePath = "";
        if (StringUtils.isEmpty(path)){
            filePath += appKey+File.separator;
        }else{
            filePath += appKey+File.separator+path+File.separator;
        }
        //全路径
        String filePath2 = relativePath + filePath ;
        File file = fileMap.get("image_ref1");
        fileName = NumUtils.getTransactionId() + "."+fileName.substring(fileName.lastIndexOf(".")+1);
        FileInputStream input = null;
        try {
            input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, "text/plain", IOUtils.toByteArray(input));
            log.info("【"+appKey+"】文件地址:"+filePath2+"-----文件名:"+fileName);
            this.uploadFile(multipartFile.getBytes(), filePath2, fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            return result;
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        String storageUrl = filePath + fileName;
        log.info("本地图片地址为：" + filePath2 + fileName);
        String image_dns = fileConfig.getImage_dns();
        log.info("图片访问的地址为："+image_dns+storageUrl);
        Map map = new HashMap();
        map.put("storageUrl",image_dns+storageUrl.replaceAll("\\\\","/"));
        map.put("relativeUrl","/"+storageUrl.replaceAll("\\\\","/"));
        result.setData(map);
        return result;
    }



    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}
